package com.ajaxlord.confluence.plugin.json.actions;

import com.atlassian.confluence.pages.AbstractPage;
import com.atlassian.confluence.pages.AttachmentManager;
import com.atlassian.confluence.pages.PageManager;
import com.atlassian.confluence.pages.actions.PageAware;
import com.atlassian.confluence.security.Permission;
import com.atlassian.confluence.spaces.Space;
import com.atlassian.confluence.util.GeneralUtil;
import org.randombits.confluence.support.sorting.NaturalTitleComparator;

import java.util.Collections;
import java.util.List;

public abstract class AbstractPageAction extends JSONActionSupport implements PageAware {
    private AbstractPage page;
    protected PageManager pageManager;
    protected AttachmentManager attachmentManager;
    private List attachments;

    public AbstractPage getPage() {
        return page;
    }

    public Space getSpace() {
        if (getPage() != null)
            return ((AbstractPage) getPage().getLatestVersion()).getSpace();

        return null;
    }

    public String getSpaceKey() {
        if (getSpace() != null)
            return getSpace().getKey();

        return null;
    }

    public void setPage(AbstractPage abstractPage) {
        this.page = abstractPage;
    }

    public boolean isPageRequired() {
        return true;
    }

    public boolean isLatestVersionRequired() {
        return true;
    }

    public boolean isViewPermissionRequired() {
        return true;
    }

    public void setPageManager(PageManager pageManager) {
        this.pageManager = pageManager;
    }

    public List getAttachments() {
        if (attachments == null) {
            attachments = attachmentManager.getLatestVersionsOfAttachments(getPage());
            Collections.sort(attachments, new NaturalTitleComparator());
        }
        return attachments;
    }

    public void setAttachmentManager(AttachmentManager attachmentManager) {
        this.attachmentManager = attachmentManager;
    }

    public boolean isPermitted() {
        if (GeneralUtil.isSuperUser(getRemoteUser()))
            return true;
        return (permissionManager.hasPermission(getRemoteUser(), Permission.VIEW, getPage()));
    }

}
